<template>
  <div class="login-page">
    <van-nav-bar
      title="账号登录"
      left-arrow
      class="a"
      @click-left="onClickLeft"
    />
    <van-form @submit="onSubmit" validate-trigger="onSubmit">
      <van-field
        v-model="username"
        name="username"
        placeholder="请输入账号"
        :rules="[
          { required: true, message: '用户名不能为空' },
          { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '密码不能为空' },
          { pattern: /^\w{5,}$/, message: '密码至少包含5个字符' }
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit"
          ><span style="font-size: 18px">登录</span></van-button
        >
      </div>
    </van-form>
    <router-link class="link" to="/register"
      ><span style="font-size: 14px">还有账号?去注册~</span></router-link
    >
  </div>
</template>

<script>
import { login } from '@/api/user'
import { setToken } from '@/utils/storage'
export default {
  name: 'login-page',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    onClickLeft () {
      this.$router.push('/register')
    },
    async onSubmit (values) {
      const data = await login(values)
      // console.log(data)

      this.$toast.success(data.description)

      if (data.status === 200) {
        setToken(data.body.token)
        this.$router.push('/')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.link {
  color: #666666;
  font-size: 12px;
  padding-right: 20px;
  display: flex;
  justify-content: center;
  padding-top: 20px;
}
// .a {
//   background-color: #21b97a;
// }
</style>
